var Texture = Class.extend({
	init: function(context, textureName, url) {
		this.textureName = textureName;
		var gl = context.renderer.gl;
		this.texture = gl.createTexture();
		this.texture.image = new Image();
		this.texture.image.owner = this;
		this.texture.image.gl = gl;
		this.texture.image.onload = this.onTextureLoaded;
		this.texture.image.crossOrigin='anonymous';
		this.loaded = false;
		this.texture.image.src = url;
	},
	
	onTextureLoaded: function() {
		this.owner.handleTextureLoaded(this.gl);
	},
	
	getWidth: function() {
		return this.texture.image.width;
	},
	
	getHeight: function() {
		return this.texture.image.height;
	},
	
	handleTextureLoaded: function(gl) {
		gl.bindTexture(gl.TEXTURE_2D, this.texture);
		//gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
		gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.texture.image);
		
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

		gl.bindTexture(gl.TEXTURE_2D, null);
		this.loaded = true;
		console.log('Texture ' + this.textureName + ' loaded');
	},
	
	isLoaded: function() {
		return this.loaded;
	},
	
	bind: function(gl) {
		gl.activeTexture(gl.TEXTURE0);
		gl.bindTexture(gl.TEXTURE_2D, this.texture);
		gl.generateMipmap(gl.TEXTURE_2D);
	},
}); 
